//
//  ONDayAheadBaseViewController.m
//  Volatix
//
//  Created by Familly on 6/19/14.
//  Copyright (c) 2014 Familly. All rights reserved.
//

#import "ONDayAheadBaseViewController.h"
#import "ONDayAheadViewController.h"
@interface ONDayAheadBaseViewController ()<ONTabbarViewControllerDelegate,ONRealTimeTableViewCellDelegate>

@end

@implementation ONDayAheadBaseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    //[super viewDidLoad];///-----> inhenrit so not super viewdidload
    
    if(self.dataArray==nil)
    {
        self.dataArray = [[NSMutableArray alloc]init];
    }
    if(self.iData==nil)
    {
        self.iData= [[NSMutableArray alloc] init];
        self.iData = [NSMutableArray arrayWithArray:[APP_DELEGATE getingDataSymbleForTypeScreen:1]];
        [self customizeData:false];
    }
    else
    {
        [self.dataArray removeAllObjects];
        [self.iData removeAllObjects];
        if(self.level==(LEVEL_ISO+1))
        {
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:[NSNumber numberWithInt:0]  forKey:@"PageIndex"];
            [params setObject:[NSNumber numberWithInt:100] forKey:@"pageSize"];
            [params setObject:self.ISO forKey:@"ISO"];
            [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_LIST_LOADZONE andPostMethodKind:enumAPIRequestMethod_GET andParams:params andString:nil inView:self.view completeBlock:^(id responseObject) {
                self.dataArray = [NSMutableArray array];
                for (id item in responseObject) {
                    ONISOObjects *isoObject = [ONISOObjects modelObjectWithDictionary:item];
                    isoObject.type=LEVEL_LOADZONE;
                    isoObject.iso=self.ISO;
                    isoObject.loadZone=nil;
                    // NSLog(@"***** %@",isoObject.name);
                    [self.iData addObject:isoObject];
                    
                }
                [self customizeData:false];
            } failureBlock:^(NSError *error) {
                
            }];

        }
        else if(self.level==(LEVEL_LOADZONE+1))
        {
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:[NSNumber numberWithInt:0]  forKey:@"PageIndex"];
            [params setObject:[NSNumber numberWithInt:100] forKey:@"pageSize"];
            [params setObject:self.ISO forKey:@"ISO"];
            [params setObject:self.LOADZONE forKey:@"LOADZONE"];
            [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_LIST_POWERPOINT andPostMethodKind:enumAPIRequestMethod_GET andParams:params andString:nil inView:self.view completeBlock:^(id responseObject) {
                ///
                self.dataArray = [NSMutableArray array];
                for (id item in responseObject) {
                    ONISOObjects *isoObject = [ONISOObjects modelObjectWithDictionary:item];
                    isoObject.iso=self.ISO;
                    isoObject.type=LEVEL_POWERPOINT;
                    isoObject.loadZone=self.LOADZONE;
                    [self.iData addObject:isoObject];
                    
                }
                [self customizeData:false];
                
            } failureBlock:^(NSError *error) {
                ///
            }];
        }
        
        

    }
    
    self.postNotifiGetData=true;
   
    [self startPullDownRefresh];
    [self initBaseColumnData];
    
    
    [self requestUpdateDataDayAhead];
    [NSTimer scheduledTimerWithTimeInterval:TIME_CHECK
                                     target:self
                                   selector:@selector(requestUpdateDataDayAhead)
                                   userInfo:nil
                                    repeats:YES];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickDone) name:SAVING_DATA_DAY_AHEAD object:nil];
    
}



- (void)viewDidAppear:(BOOL)animated {
    ///[super viewDidAppear:animated];///-----> inhenrit so not super viewDidAppear
    self.postNotifiGetData=false;
     [self initDelegateDayAHeadTabbar:true];
//    [Utils setTypeScreen:1];
//    [Utils setMainScreen:(self.level==LEVEL_ISO)?true:false];
}
-(void)viewWillAppear:(BOOL)animated
{
    ///[super viewWillAppear:animated];///-----> inhenrit so not super viewWillAppear
    [Utils SetISO:self.ISO andLoadZone:self.LOADZONE];
    self.postNotifiGetData=true;
    ONTabbarViewController *tabbar =(ONTabbarViewController*)self.tabBarController;
    [Utils setTypeScreen:1];
    [Utils setMainScreen:(self.level==LEVEL_ISO)?true:false];
    [tabbar.ButtonLeft setImage:[UIImage imageNamed:(self.level==LEVEL_ISO)?@"btn_add.png":@"arrow_left.png"] forState:UIControlStateNormal];
    [self initDelegateTabbar:true];
     self.tabBarController.title = (self.level==(LEVEL_ISO+1))?[NSString stringWithFormat:@"LOADZONE-%@",self.ISO]:(self.level==(LEVEL_LOADZONE+1))?[NSString stringWithFormat:@"POWERPOINT-%@",self.LOADZONE]:@"DAY AHEAD";
    self.filerData =[NSMutableArray arrayWithArray:[APP_DELEGATE getingFilterBySymble:[self getRequestFiter:1]]];//[NSMutableArray arrayWithArray:[APP_DELEGATE getingFilterTimerForTypeScreen:1]];
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    ///[super viewWillDisappear:animated];///-----> inhenrit so not super viewWillDisappear
    
    // Get current controller
    if ([self.navigationController.visibleViewController isKindOfClass:[ONAddSymbolViewController class]]) {
        
        ONAddSymbolViewController *controller = (ONAddSymbolViewController *)self.navigationController.visibleViewController;
        controller.addSymbolItemsArray = self.dataArray;
        controller.typeScreen=1;
        // current data
        controller.currentRealTimeData = [[NSMutableArray alloc]init];
        for ( ONISOObjects *oNISOObject in self.dataArray){
            [controller.currentRealTimeData addObject:oNISOObject];
        }
        
    } else if ([self.navigationController.visibleViewController isKindOfClass:[ONSettingsViewController class]]) {
        ONSettingsViewController *controller = (ONSettingsViewController *)self.navigationController.visibleViewController;
        controller.dataArray=self.dataArray;
        
        
    }
  
}


-(void)initBaseColumnData
{
    if(self.columnArray==nil){
        self.columnArray = [[NSMutableArray alloc]init];
    }
    for (int i=0; i<4; i++)
    {
        ONColumnTitleObject *column = [[ONColumnTitleObject alloc]init];
        column.allowToSelect = NO;
        column.mainColumn=1;
        switch (i) {
            case 0:
                column.name = @"Point";
                break;
            case 1:
                 column.name = @"Price";
                break;
            case 2:
                 column.name = @"Loss";
                break;
            case 3:
                 column.name = @"Congestion";
                break;
            default:
                break;
        }
        [self.columnArray addObject:column];
      
        
    }
    [self.columnArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        ONColumnTitleObject *p1 = (ONColumnTitleObject*)obj1;
        ONColumnTitleObject *p2 = (ONColumnTitleObject*)obj2;
        
        if (p1.mainColumn < p2.mainColumn) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if (p1.mainColumn > p2.mainColumn) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
        
        
    }];
    
    
}




#pragma mark - UITableViewDataSource Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    
//    NSInteger numberOfCell = 0;
//    if (self.isShowingSelectColumnView) {
//        numberOfCell = [self.columnMenuArray count]+[self.dataArray count];
//    } else {
//        numberOfCell = [self.dataArray count];
//    }
    return [self.dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kHeightSection;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(self.isShowingSelectColumnView)
    {
        return 30;
    }
    return ([self isInVisibleArray:[self.dataArray objectAtIndex:indexPath.row]])?0:30;
    
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *sectionView = [[UIView alloc]init];
    sectionView.backgroundColor = [UIColor clearColor];
    
    CGFloat currentX = 0;
    
    for (int i=0; i<[self.columnArray count]; i++) {
        
        
        ONRealTimeSectionView *view = [[ONRealTimeSectionView alloc]initWithFrame:CGRectMake(0, 0, kWidthColumn, kHeightSection)];
        ONColumnTitleObject *column =[self.columnArray objectAtIndex:i];
        //NSLog(@"column.name  %@",column.name);
        view.titleLabel.text = column.name;
        
        currentX = i*kWidthColumn;
        
        view.frame = CGRectMake(currentX, 0, kWidthColumn, kHeightSection);
        sectionView.frame = CGRectMake(0, 0, currentX + kWidthColumn, kHeightSection);
        
        [sectionView addSubview:view];
    }
    
    return sectionView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *reuseIdentifier = @"ONRealTimeTableViewCell";
    
        ONRealTimeTableViewCell *cell = (ONRealTimeTableViewCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (!cell) {
            cell = (ONRealTimeTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:reuseIdentifier owner:self options:nil] objectAtIndex:0];
            cell.delegate=self;
        }
    //NSLog(@"%ld",(long)[self.dataArray count]);
    if(indexPath.row>=[self.dataArray count]){return cell;}
        ONISOObjects *oNISOObject = [self.dataArray objectAtIndex:indexPath.row];
        [cell loadCellData_DayAhead:oNISOObject withDataUpdate:self.dataUpdate andCurrentChoiced:self.currentMenuIndex andNumberColumn:kNumberOfColumnOnRealTime andShowArrow:true];
        cell.hidden=[self isInVisibleArray:oNISOObject];
        return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // Set background color of cell here if you don't want default white
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // not yet lgoin
    if (![self userIsLogin]) {
        [self showLoginScreen];
        // Deselect the row
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }
    
    ONISOObjects *selected =[self.dataArray objectAtIndex:indexPath.row];

    if([self checkingHasChildByName:selected.name])
    {
        ONDayAheadBaseViewController *vc=(ONDayAheadBaseViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ONDayAheadViewController"];
        vc.iData=[NSMutableArray arrayWithArray:self.iData];
        ONISOObjects *oNISOObject = [self.dataArray objectAtIndex:indexPath.row];
        if(oNISOObject.type==LEVEL_ISO)
        {
            vc.ISO = oNISOObject.name;
        }
        else if(oNISOObject.type==LEVEL_LOADZONE)
        {
            vc.ISO = oNISOObject.iso;
            vc.LOADZONE = oNISOObject.name;
        }
        else
        {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
             return;
        }
        vc.level=oNISOObject.type+1;
        vc.columnArray=[NSMutableArray arrayWithArray:self.dynamicColumnBackUp];
         NSLog(@"ISO %@ - LOADZONE %@ ",vc.ISO,vc.LOADZONE);
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    // Deselect the row
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Tabbar Delegate


-(void)initDelegateDayAHeadTabbar:(BOOL)value
{
    ONTabbarViewController *_tabbar =(ONTabbarViewController*)self.tabBarController;
    if(value){
        _tabbar.tabbarDelegateDayAhead=self;
        [self updateColumnNameDayAHead:_tabbar.arrDayAheadResult];
        
    }
    else
    {
        _tabbar.tabbarDelegateDayAhead=nil;
    }
}




-(void)customizeData:(BOOL)value
{
    if(value&&(self.level==LEVEL_ISO))
    {
        [APP_DELEGATE savingDataSymble:self.iData andTypeScreen:1];//savingDataSymble:self.iData andRealtime:false];
    }
    self.dataArray =[NSMutableArray arrayWithArray:self.iData];
    /// sort data
    [self.dataArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        ONISOObjects *p1 = (ONISOObjects*)obj1;
        ONISOObjects *p2 = (ONISOObjects*)obj2;
        
        if (p1.type > p2.type) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if (p1.type < p2.type) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
        
        
    }];
    
    
    [self.tableView reloadData];
    
    
}
-(void)clickNext:(ONISOObjects *)ISOObject
{
    NSLog(@"%s",__FUNCTION__);
    ONDayAheadViewController *priceDetailVC=[[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"ONDayAheadViewController_detail"];
    priceDetailVC.columnDynamic =self.dynamicColumnBackUp;
    priceDetailVC.currentISOObject = ISOObject;
    [self.navigationController pushViewController:priceDetailVC animated:true];

}
#pragma mark - Request And Call Back  Methods Webservice
- (void)requestGetData {
    
    NSLog(@"REQUEST RELOAD DATA");
    [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_DAY_AHEAD object:self.dataArray userInfo:nil];
}
-(void)updateDataDayAhead:(NSMutableArray *)sender
{
    NSLog(@"%s",__FUNCTION__);
    self.dataUpdate =[NSMutableArray arrayWithArray:sender];
    [self.tableView reloadData];
    [self doneLoadingTableViewData];
}
-(void)requestUpdateDataDayAhead
{
    if(self.postNotifiGetData==true)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_DAY_AHEAD object:self.dataArray userInfo:nil];
    }
}

-(void)updateColumnNameDayAHead:(NSMutableArray *)sender
{
    // NSLog(@"DAY AHEAD Number Column %ld",(long)[sender count]);
    ///------------ UPDATE COLUMN DYNAMIC ----------//
    int iDynamicColumn =(int)[sender count];
    
    /// remove  dynamic column
    // NSLog(@"self.columnArray %ld",(long)[self.columnArray count]);
    
    
    NSMutableArray * tempRemove= [[NSMutableArray alloc] init];
    for (int index = 0; index < [self.columnArray count]; index++) {
        ONColumnTitleObject *column =[self.columnArray objectAtIndex:index];
        if(column.mainColumn==1)
        {
            [tempRemove addObject:column];
        }
    }
    
    self.columnArray = [NSMutableArray arrayWithArray:tempRemove];
    
    self.dynamicColumnBackUp =[[NSMutableArray alloc] init];
    for (int index=0; index<iDynamicColumn; index++)
    {
        ONObjectColumn  *item =[sender objectAtIndex:index];
        ONColumnTitleObject *column = [[ONColumnTitleObject alloc]init];
        
        column.name = [NSString stringWithFormat:@"%@",item.nameColumn];
        column.allowToSelect = NO;
        column.mainColumn=0;
        // NSLog(@"****** %@ ***** %d ",[NSString stringWithFormat:@"%@",item.nameColumn],column.mainColumn);
        
        [self.columnArray addObject:column];
        [self.dynamicColumnBackUp addObject:column];
        
    }
    // Saving Dynamic Column Name
    /////-------------------------------------->
    [APP_DELEGATE savingListDynamicColumnName:self.dynamicColumnBackUp andRealTime:false];
    
    
    
    int kColumnOnRealTime =3+iDynamicColumn;
    kNumberOfColumnOnRealTime=kColumnOnRealTime;
    /// update UI
    [self updateUIForViewWithColumn:kColumnOnRealTime];
    [self.tableView reloadData];
}
#pragma mark - CLICK DONE DELEGATE
-(void)clickDone
{
    NSLog(@"DAY AHEAD %s",__FUNCTION__);
    self.iData =[NSMutableArray arrayWithArray:self.dataArray];
    [self customizeData:true];
    [self requestGetData];
    
}

-(void)dealloc
{
    [self initDelegateTabbar:false];
    [self initDelegateDayAHeadTabbar:false];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SAVING_DATA_DAY_AHEAD object:nil];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
